%%% ------------------------------------------------------------------
%%% Licensed under the Apache License, Version 2.0 (the 'License');
%%%  you may not use this file except in compliance with the License.
%%%  You may obtain a copy of the License at
%%%
%%%      http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Copyright (c) 2018 qingchuwudi <bypf2009@vip.qq.com>
%%%
%%%  Unless required by applicable law or agreed to in writing, software
%%%  distributed under the License is distributed on an 'AS IS' BASIS,
%%%  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%%  See the License for the specific language governing permissions and
%%%  limitations under the License.
%%%
%%% @doc
%%% @author  qingchuwudi <'bypf2009@vip.qq.com'>
%%% @copyright 2018 qingchuwudi <bypf2009@vip.qq.com>
%%% @end
%%% created|changed : 2018-02-09 12:11
%%% coding : utf-8
%%% ------------------------------------------------------------------
-module(streetlight).
-author("qingchuwudi").

%% API exports
-export([decode/1]).
-export([encode/1]).

%%=====================================================================================
%% Micro Defination
%%=====================================================================================
-define(OFF   , 0).
-define(ON    , 1).
-define(AIMING, 2).
-define(GET   , 3).
-define(REPORT, 8).

-type de_data() :: {ok, map()} | error.
-type en_data() :: {ok, binary()} | error.

%%=====================================================================================
%% API functions
%%=====================================================================================

%%@doc 解码路灯数据
-spec decode(FRMPayload) -> DeData when
             FRMPayload :: binary(),
             DeData     :: de_data().
%% turn on|off
decode(<<Cmd:8, Volt:16/big-integer, Elec:16/big-integer,
         Signal:16/big-signed-integer, Level:8>>)
        when (0 =< Level andalso Level =< 100) ->
    {ok, #{<<"cmd">>   => ?REPORT, <<"volt">>   => Volt,
           <<"elec">>  => Elec,    <<"signal">> => Signal,
           <<"level">> => Level,   <<"open">>  => open(Cmd)}};

decode(_FRMPayload) -> error.

%%@doc 编码路灯数据
-spec encode(Json) -> EnData when
             Json :: maps:map(),
             EnData :: en_data().
encode(#{<<"cmd">> := ?OFF}) ->
    {ok, <<?OFF>>};
encode(#{<<"cmd">> := ?ON}) ->
    {ok, <<?ON>>};
encode(#{<<"cmd">> := ?AIMING, <<"level">> := Level}) ->
    {ok, <<?AIMING, Level>>};
encode(#{<<"cmd">> := ?GET}) ->
    {ok, <<?GET>>};
encode(_Json) ->
    undefined.

%%=====================================================================================
%% Internal functions
%%=====================================================================================
open(?OFF) -> ?OFF;
% open(?ON) -> ?ON;
open(_) -> ?ON.
